package com.example.qggoodsconsumer.controller;

import com.example.qgcommon.util.RedisUtil;
import com.example.qgcommon.util.ReturnUtil;
import com.example.qggoodsconsumer.service.LocalGoodsService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
public class GoodsController {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private LocalGoodsService service;

    @RequestMapping("/getAllGoods")
    public Map getAllGoods(){
//        return service.getAllGoods();
        List<Map> allGoods = service.getAllGoods();

        if (allGoods==null||allGoods.size()==0){
            return ReturnUtil.fail();
        }else{
            return ReturnUtil.success(allGoods);
        }

    }

    @RequestMapping("/getAllGoodsByQgTotal")
    public Map getAllGoodsByQgTotal(){
        List<Map> allGoodsByQgTotal = service.getAllGoodsByQgTotal();
        if (allGoodsByQgTotal==null||allGoodsByQgTotal.size()==0){
            return ReturnUtil.fail();
        }else{
            return ReturnUtil.success(allGoodsByQgTotal);
        }
    }
    //进行抢购
    @RequestMapping("/qg")
    public Map  qg(@RequestParam Map map) throws JsonProcessingException {
        //根据token获取用户的id
        String userJson = redisUtil.getStr( "token:" + map.get( "token" ));
        Map user = new ObjectMapper().readValue(userJson,Map.class);
        //获得用户id
        int userId = (Integer) user.get( "id" );
        //把用户id保存到参数map这
        map.put("userId",userId);
        //re :1 抢购成功 -1 库存不足
        int re =  service.qg( map );
        if (re == 1){
            return ReturnUtil.success(re);
        }else{
            return ReturnUtil.fail();
        }

    }

    @RequestMapping("/flushResult")
    public Map  flushResult(@RequestParam Map map) throws JsonProcessingException {

        String userJson = redisUtil.getStr( "token:" + map.get( "token" ));
        Map user = new ObjectMapper().readValue(userJson,Map.class);
        //获得用户id
        int userId = (Integer) user.get( "id" );
        map.put("userId",userId);

        int qgResult = service.getQgResult( map );

        if (qgResult==1){
            return ReturnUtil.success();
        }else if (qgResult==-2){
            return ReturnUtil.fail(qgResult+"");
        }else{
            //没有结果
            return ReturnUtil.fail();
        }


    }

    }
